import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import suit.persist.Persist;
import suit.persist.PersistException;
import suit.ui.Application;
import suit.ui.Box;
import suit.ui.Button;
import suit.ui.Entry;
import suit.ui.Label;
import suit.ui.Screen;
import suit.ui.ScrolledWindow;
import suit.ui.themes.DefaultTheme;

public class PersistDemo extends Application implements Button.Clicked {

	Screen main;

	Box vbox;
	Box hbox;

	Entry entry;
	Button add;
	Button del;
	ScrolledWindow scroller;
	Label output;

	Persist persist;

	public PersistDemo() {

		main = new Screen(new DefaultTheme());

		hbox = new Box(Box.Horiz, true, 10);
		vbox = new Box(Box.Vert, true, 10);

		entry = new Entry();
		add = new Button("Add");
		add.connect(this);
		del = new Button("Delete");
		del.connect(this);

		hbox.pack(entry, true, true, 0);
		hbox.pack(add, false, true, 0);
		hbox.pack(del, false, true, 0);

		scroller = new ScrolledWindow(true, false);
		scroller.setBorderWidth(10);

		output = new Label();
		output.setAlign(Label.TOP | Label.LEFT);

		vbox.pack(hbox, false, true, 0);
		vbox.pack(output, true, true, 0);

		scroller.add(vbox);

		main.add(scroller);
		setScreen(main);

		setText();

	}

	public void setText() {
		try {
			if( persist == null ) persist = new Persist();
			output.setText(persist.get().getJSONArray("items").toString(4));
		} catch (PersistException e) {
			output.setText(e.getMessage());
		} catch (JSONException e) {
			output.setText("There is no information.");
		}
	}

	public boolean onKeyPressed(int key) {
		if (key == -8)
			notifyDestroyed();
		return false;
	}

	public void onClicked(Button source) {
		String text = entry.getText();
		try {
			JSONObject object = persist.get();
			if (!object.has("items"))
				object.put("items", new JSONArray());
			if (source.equals(add)) {
				object.getJSONArray("items").put(text);
				persist.flush();
				setText();
				entry.setText("");
			} else if (source.equals(del)) {
				JSONArray items = object.getJSONArray("items");
				if (items.length() > 0) {
					entry.setText(items.remove(items.length() - 1).toString());
					persist.flush();
					setText();
				}
			}
		} catch (PersistException e) {
			output.setText(e.getMessage());
		} catch (JSONException e) {
			output.setText(e.getMessage());
		}
	}
}
